<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="defaultprops" default-expand-all :expand-on-click-node="false">
        <template #default="{data}">
          <el-row style="width: 100%;" type="flex" justify="space-between">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="manager">{{ data.managerName }}</span>
              <el-dropdown @command="operateDept($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑子部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add-dept ref="addDept" :current-id="currentId" :show-dialog.sync="showDialog" @updateDepartment="getDepartment" />
  </div>
</template>
<script>
import { delDepartment, getDepartment } from '@/api/department'
import { tranlateListTree } from '@/utils'
import addDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    addDept
  },
  data() {
    return {
      depts: [],
      defaultprops: {
        label: 'name'
      },
      showDialog: false,
      currentId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      // console.log(res)
      this.depts = tranlateListTree(res, 0)
    },
    operateDept(type, id) {
      // console.log(type)
      if (type === 'add') {
        this.showDialog = true
        this.currentId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentId = id
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        this.$confirm('您确认要删除吗')
          .then(async() => {
            await delDepartment(id)
            this.$message.success('删除成功')
            this.getDepartment()
          })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 30px 40px;
  font-size: 14px;
}
.manager{
width:100px;
display: inline-block;
// background-color: red;
}
</style>
